package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.message.domain.entity.PushEntity;
import com.xbongbong.message.domain.entity.PushSetEntity;
import com.xbongbong.paas.pojo.dto.PaymentSheetDataDTO;
import com.xbongbong.paas.script.pojo.dto.ScriptBaseDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.message.enums.MessagePushRefTypeEnum;
import com.xbongbong.pro.message.enums.MessageWebPcUrlEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.message.model.PushSetModel;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 消息相关问题修复接口
 * @author 魏荣杰
 * @date 2019/11/25 10:59 上午
 * @since v4.6.0
 * @version v4.6.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/message")
public class MessageScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(MessageScriptController.class);

    /**
     * 大于这个时间点的数据才做处理
     */
    private Integer pushTime = 1572883200;

    @Resource
    private PushModel pushModel;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private PushSetModel pushSetModel;

    @RequestMapping(value = "/fixCustomerChange", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String returnCustomer2Public(@RequestBody @Valid ScriptBaseDTO scriptBaseDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                String key = scriptBaseDTO.getXbbCode();
                if (!Objects.equals(key, proBaseConfig.getXbbCode())) {
                    LOG.error("fixCustomerChange 密码错误，停止定时任务！");
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100066);
                }
                Map<String, Object> param = new HashMap<>();
                param.put("type", PushTypeEnum.CUSTOMER_CHANGE_PUSH.getCode());
                param.put("subType", PushTypeEnum.CUSTOMER_CHANGE_PUSH.getSubCode());
                param.put("startPushTime", pushTime);
                Integer entitysCount = pushModel.getEntitysCount(param);
                Integer pageSize = 100;
                Integer pageNum = entitysCount / pageSize + 1;
                for (int i = 1 ; i <= pageNum ; i++) {
                    int start = (i - 1) * pageSize;
                    int end = i * pageSize;
                    param.put("start", start);
                    param.put("pageNum", end);
                    LOG.info("start=" + start + ", end=" + end + ", total=" + entitysCount);
                    List<PushEntity> entitys = pushModel.findEntitys(param);
                    Map<String, Object> optionMap = new HashMap<>();
                    for (PushEntity pushEntity : entitys) {
                        String refType = pushEntity.getRefType();
                        PushRefTypePojo pushRefTypePojo = JSON.parseObject(refType, PushRefTypePojo.class);
                        JSONObject refTypeJson = JSONObject.parseObject(refType);
                        JSONObject optionsObj = refTypeJson.getJSONObject("options");
                        PushRefTypePojo.CommonDetailOptions options = JSONObject.parseObject(optionsObj.toJSONString(), PushRefTypePojo.CommonDetailOptions.class);
                        Integer businessType = options.getBusinessType();
                        if (!Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_STAGE.getCode())) {
                            continue;
                        }

                        options.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                        optionMap = BeanUtil.convertBean2Map(options);
                        pushRefTypePojo.setPcUrl(formatPcUrl(MessageWebPcUrlEnum.COMMON_DETAIL.getUrl(), optionMap));
                        pushRefTypePojo.setOptions(options);
                        pushRefTypePojo.setType(MessagePushRefTypeEnum.COMMON_DETAIL.getAlias());

                        pushEntity.setRefType(JSON.toJSONString(pushRefTypePojo));

                        pushModel.update(pushEntity);
                    }
                }
                LOG.info("fixCustomerChange finish");
            } catch (Exception e) {
                LOG.error("fixCustomerChange fail", e);
            }

            response = new XbbResponse<>(new BaseVO());
        }
        return JSON.toJSONString(response);
    }



    /**
     * 工作报告-未交报告提醒和逾期未交报告提醒设置
     * pushObject 中刷一个"justCheckSelf":true，默认勾选推送给主管
     *
     * @param paymentSheetDataDTO
     * @return
     */
    @RequestMapping(value = "/addWorkReportParam", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addWorkReportParam(@RequestBody @Valid PaymentSheetDataDTO paymentSheetDataDTO) throws XbbException{
        if (!proBaseConfig.getXbbCode().equals(paymentSheetDataDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        List<String> corpidList = Objects.isNull(paymentSheetDataDTO.getCorpidList()) ? new ArrayList<>() : paymentSheetDataDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        long timeStart = DateTimeUtil.getInt();
        LOG.info("总共有多少家需要处理的公司:{}", corpidList.size());
        Map<String, Object> param = new HashMap<>();
        //del = 1 和 0 的都要刷
        //param.put("del", BasicConstant.ZERO);
        param.put("type",XbbRefTypeEnum.WORK_REPORT.getCode());
        param.put("subTypeIn", Arrays.asList(PushTypeEnum.WORK_REPORT_REMIND_PUSH.getSubCode(),PushTypeEnum.WORK_REPORT_OVERDUE_PUSH.getSubCode()));
        int i = 0;
        for (String corpid : corpidList) {
            i++;
            LOG.info("现在是第{}家公司, corpid:{}", i, corpid);
            param.put("corpid", corpid);
            List<PushSetEntity> entitys = pushSetModel.findEntitys(param);
            if (CollectionsUtil.isEmpty(entitys)) {
                continue;
            }
            for(PushSetEntity pushSetEntity : entitys){
                JSONObject jsonObject = JSON.parseObject(pushSetEntity.getPushObject());
                JSONObject manager = jsonObject.getJSONObject("manager");
                if (manager != null){
                    if (!manager.getBooleanValue("justCheckSelf")){
                        manager.put("justCheckSelf",false);
                    }
                }
                jsonObject.put("manager",manager);
                pushSetEntity.setPushObject(JSON.toJSONString(jsonObject));
            }
            if (CollectionsUtil.isNotEmpty(entitys)) {
                pushSetModel.updateBatch(entitys,corpid);
            }
        }
        LOG.info("-----------time consume addWorkReportParam:" + (DateTimeUtil.getInt() - timeStart));
        return JSON.toJSONString("{\"msg\":\"success\"}");
    }




    private String formatPcUrl(String url, Map<String, Object> options) {
        String params = null;
        for (Map.Entry<String, Object> entry : options.entrySet()) {
            if (params == null) {
                params = entry.getKey() + "=" + entry.getValue();
            } else {
                params += "&" + entry.getKey() + "=" + entry.getValue();
            }
        }
        return url + "?" + params;
    }
}
